<?php
/**
 * Created by Chukintang on 2018/5/18 21:56.
 */
namespace utils;

/**
 * Generates Random String
 * Class RandomStringGenerator
 * @package utils
 */
class RandomStringGenerator
{
    /**
     * Generates a random string of defined length
     *
     * @param $length
     * @return string
     */
    public static function generate($length,$type = 0,$charlist = '',$prefix = '')
    {
        $random = "";
        switch ($type){
            case 0:
                if(empty($charlist)){
                    $charlist = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%&*?";
                }
                $random = self::getRamdomStringFromList($length,$charlist);
                break;
            case 1:
                if(empty($charlist)){
                    $charlist = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
                }
                $random = self::getRamdomStringFromList($length,$charlist);
                break;
        }
        return substr($prefix.$random,0,$length);
    }

    /**
     * genarate a ramdom string from charlist
     * @desc genarate a ramdom string from charlist
     */
    private static function getRamdomStringFromList($length,$charlist){
        $i = 0;
        $random = "";
        while ($i < $length) {
            $random .= $charlist{mt_rand(0, (strlen($charlist) - 1))};
            $i++;
        }
        return $random;
    }
}